<?

class CPalinsesto_vidwiz extends Controller_vidwiz    //WARNING: PHP5 does not support multiple inheritance but there is more than 1 superclass defined in your UML model!
{

    /**
     * Inserisce il palinsesto nel database
     * @param array $videos Gli id dei video del palinsesto
     * @param string $onairDate Y-m-d
     * @param string $title Il titolo del plainsesto
     * @access public
     */
    public function createPalinsesto( $videos,  $onairDate , $title) {
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $model = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $entity = USingleton_vidwiz::getInstances("EPalinsesto_vidwiz");
        $error[] = $check->check_title($title);
        $error[] = $check->check_videoList($videos);
        $error[] = $check->check_date($onairDate);
        
        
        $onairDate = $model->dateToISO($onairDate);
        if(in_array(false, $error))
            die(__("C'è stato un errore nel trasferimento dei dati",'vidwiz-plugin'));
        $pal = $entity->generateObject(array(
            "videoList" => $videos,
            "onairDate" => $onairDate,
            "title"     => $title,
            "author"    => $model->getUsername()
        ));        
        $query = $model->insertQuery($pal);
        $model->executeQuery($query);
    } // end of member function createPalinsesto

    /**
     * Aggiorna il palinsesto in base alle informazioni passate
     * @param type $palInfos (
     */
    public function updatePalinsesto($palid,$palInfos ) {
        $MPal = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $fields=array(); $i=0; global $config;
        foreach($palInfos as $key=>$value){
            $fields[$i][] = $key;
            $fields[$i][] = $value;
            $i++;
        }
        $query = $MPal->updateQuery($config['tables']['palinsesto'],$fields,array(array("id","=",$palid)));
        $MPal->executeQuery($query);
        
    } // end of member function updatePalinsesto

    /**
     * Ritorna l'id del prossimo video del palinsesto attivo o la prossima breaking
     * news
     * @return string
     */
    public function getNextVideo() {
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $session = USingleton_vidwiz::getInstances("USession_vidwiz");
        $view = USingleton_vidwiz::getInstances("View_vidwiz");
        $MPal = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $MVideo = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $CVideo = USingleton_vidwiz::getInstances("CVideos_vidwiz");
        global $config;
        $palinsesto = $MPal->getLastPalinsesto();
        $palinsesto = $palinsesto[0];
        $palinsestoClient = $session->getSession('palinsesto_id');
        $prev = $view->getRequest("prev");
        
        $session->setSession('palinsesto_list',$palinsesto['videoList']);
        if($palinsesto['id'] != $palinsestoClient || $palinsestoClient == false){
            $session->setSession('palinsesto_id',$palinsesto['id']);
            $session->deleteSessionVar('palinsesto_watched');
            $session->setSession('palinsesto_watched',array());
            $nextVideo = explode(",",$palinsesto['videoList']);
            $watched = array();
            }
        else{
            $watched = $session->getSession('palinsesto_watched');
            if($watched == "")
                $watched = array();
            if($prev != "" && $prev != false && $prev != "false"){
                $watched[] = $prev;
            }
            $nextVideo = explode(",",$palinsesto['videoList']);
            $nextVideo = array_diff($nextVideo, $watched);
            if(count($nextVideo)==0){
                $session->setSession('palinsesto_id',$palinsesto['id']);
                $session->setSession('palinsesto_watched',array());
                $nextVideo = explode(",",$palinsesto['videoList']);
                $watched = array();
            }
        }
        $session->setSession('palinsesto_watched',$watched);
        $video = $MVideo->getVideoFromId(reset($nextVideo));
        $video[0] = $this->absPathInArray($video[0], array('file_position'));
        $video_palinsesto["video"] = $video;
        $video_palinsesto["palinsesto"] = $palinsesto;
        return $video_palinsesto;
    } // end of member function getNextVideo

    /**
     * Ritorna il tpl del palinsesto attuale
     *
     * @return string
     * @access public
     */
    public function getActualPalinsestoFrontend() {
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $view = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        $video_palinsesto = $this->getNextVideo();
        return $view->getPalinsestoFrontend($video_palinsesto['video'],$video_palinsesto['palinsesto']);
    } // end of member function getActualPalinsesto

    /**
     * Permette la ricerca all'interno della creazione del palinsesto
     * @global type $config
     * @param string $date Y-m-d
     * @param string $metatags
     * @param string $category
     * @param string $limitUp Quanti risultati deve visualizzare
     * @param string $limitDown indica da quale video bisogna partire nel reperimento dei risultati
     * @return array i risultati della ricerca
     */
    public function searchVideosPalinsesto($date,$metatags,$category,$limitUp,$limitDown = "0"){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MPal =  USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $CVideos = USingleton_vidwiz::getInstances("CVideos_vidwiz");
        global $config; $where = false;
        if($limitUp == "")
            $limitUp=$config["searchLimitPalinsestoAdmin"];
        if(isset($date) && !is_null($date) && $date!=""){
            $date = explode("/", $date);
            $date =  $date[2]."-".$date[1]."-".$date[0]." 00:00:00";
            $where[] = array("upload_date",">=",$date);
        }
        if(isset($category) && !is_null($category) && $category!="" && $category != "undefined"){
            $where[] = array("category","=",$category);
        }
        $where[] = array("converted","=","1");
        $metatagsArr = array();
        $metatags = explode(",",$metatags);
        
        foreach($metatags as $key=>$value){
            $metatagsArr[] = $value;

        }
        
        foreach($metatagsArr as $key=>$value)
            $where[] = array("metatags"," LIKE ","'%".$value."'");
        
        $query = $MPal->searchQuery($config['tables']['videos'], $where, array("*"), $limitDown.",".$limitUp,"id DESC");
        
        $rows = $MPal->getRowsAssoc($query);
       // if(isset($metatags) && !is_null($metatags) && $metatags!="")
       //     $rows = $CVideos->searchMetatags($metatags,$rows);
        foreach($rows as $key => $value)
            $rows[$key] = $this->absPathInArray($value, array("file_position","thumb"));
        return $rows;
    }

    /**
     * A partire dai parametri passati, ritorna un array contenente due booleani. Questi indicano
     * se esistono pagine precedenti o successive all'attuale pagina di risultati
     * @param string $date
     * @param string $metatags
     * @param string $category
     * @param string $limitDown
     * @param string $limitUp
     * @return array 
     */
    public function checkPagination($date,$metatags,$category,$limitDown,$limitUp = 16){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $return['fwd'] = true;   $return['bck'] = true;
        $limitDownNext = (int)$limitDown+(int)$limitUp;
        
        $results = $this->searchVideosPalinsesto($date,$metatags,$category,$limitUp,$limitDown);
        $nextResults = $this->searchVideosPalinsesto($date,$metatags,$category,$limitUp,$limitDownNext);
        $nrResults = count($results);
        $nrNextResults = count($nextResults);
        if(($nrResults < (int)$config["searchLimitPalinsestoAdmin"]) || ($nrResults == (int)$config["searchLimitPalinsestoAdmin"] && $nrNextResults == 0))
            $return['fwd'] = false;
        if($limitDown == 0)
            $return['bck'] = false;     
        return $return;
        
    }
    
    public function insertBreakingNews($breaking){
        $MPal = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $lastPalinsesto = $MPal->getLastPalinsesto();
        $lastPalinsesto = $lastPalinsesto[0];
        $list = explode(",", $lastPalinsesto['videoList']);
        if(in_array($breaking['id'], $list))
                return;
        $newList[0] = $breaking['id'];
        $newList = array_merge($newList,$list);
        $lastPalinsesto['videoList'] = implode(",",$newList);
        $this->updatePalinsesto($lastPalinsesto['id'],$lastPalinsesto);
        
    }
    
    public function vidwiz_vid_palinsesto_or_home_page($home = false){
        $VPal = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        
        $CVideos = USingleton_vidwiz::getInstances("CVideos_vidwiz");
        $model = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        //Inizializza la sessione, necessario per far funzionare la paginazione
        //infatti quelle eliminate sono le variabili che sono utilizzate dalle funzioni
        //che gestiscono la paginazione. Quando si accede alla pagina, queste 
        //devono essere eliminate
        $session = USingleton_vidwiz::getInstances("USession_vidwiz");
        $session->deleteSessionVar("categorySearch");
        $session->deleteSessionVar("dateSearch");
        $session->deleteSessionVar("metatagSearch");
        //Setta il limit di default x la ricerca
        $session->setSession("limit",$config["searchLimitPalinsestoAdmin"]);
        $session->setSession('lastLimitDown',"0");
        
        $paginationCheck = $this->checkPagination(null,null,null,"0",$config["searchLimitPalinsestoAdmin"]);
        $results = $CVideos->getLastVideos((int)$config["searchLimitPalinsestoAdmin"]);
        foreach ($results as $key => $value){
            $results[$key] = $CVideos->absPathInArray($value,array('file_position','thumb'));
            }
        $cats = $CVideos->getCategories();
        $username = $model->getUsername();
        if($home == false)
            return $VPal->getPalinsestoCreationPage($results,$cats,$username,$paginationCheck['fwd']);
        else
            return $VPal->getHomePage($results,$cats,$paginationCheck['fwd']);
    }
    
    public function vidwiz_searchVideosPalinsesto($from_home = false){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $session = USingleton_vidwiz::getInstances("USession_vidwiz");
        $VPal = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        global $config;
        $category = $VPal->getRequest("categorySearch");
        $date = $VPal->getRequest("dateSearch");
        $metatags = $VPal->getRequest("metatagSearch");
        $limit = $VPal->getRequest("limit");
        $home = $VPal->getRequest("home");
        
        if($home != false)  $from_home = true;
        if($limit == false || $limit == "" || !isset($limit))
            $limit = $config["searchLimitPalinsestoAdmin"];
        
        //salva i dati della ricerca nella sessione
        $session->setSession('categorySearch',$category);
        $session->setSession('dateSearch',$date);
        $session->setSession('metatagSearch',$metatags);
        $session->setSession('limit',$limit);   
        $session->setSession('lastLimitDown',"0");
        $results = $this->searchVideosPalinsesto($date,$metatags,$category,$limit);
        if(count($results) != 0)
            if($from_home == false){
                return $VPal->getResultsVideosSearchPalinsesto($results);}
            else{
                return $VPal->getResultsVideosSearchHome($results);
                }
        else
            return false;
    }
    
    public function vidwiz_nextVideoPalinsesto(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MVideo = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $MVideo->checkValidBreakingNews();
        $video_palinsesto = $this->getNextVideo();
        $video = $video_palinsesto["video"][0]; $output = "";
        $output .= "|beg|";
        foreach($video as $key=>$value){
            $output .= $key."|x|".$value."|xxx|";
        }
        $palinsesto = $video_palinsesto['palinsesto'];
        $output .= "|end|";
        return $output;
    }
    
    public function vidwiz_paginationPalinsesto(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $session = USingleton_vidwiz::getInstances("USession_vidwiz");
        $VPal = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        $category = $session->getSession("categorySearch");
        $date =  $session->getSession("dateSearch");
        $metatags =  $session->getSession("metatagSearch");
        $limitUp =  $session->getSession("limit");
        $lastLimitDown = $session->getSession('lastLimitDown');
        $home = $VPal->getRequest('home');
        $fwd_bck = $VPal->getRequest('fwd_bck');
        if($fwd_bck == "fwd"){
            $limitDown = (int)$lastLimitDown + (int)$limitUp;
            }
        else{
            $limitDown = (int)$lastLimitDown - (int)$limitUp;
            }
        $limitDown = (string)$limitDown;
        $session->setSession("lastLimitDown",$limitDown);
        $results = $this->searchVideosPalinsesto($date,$metatags,$category,$limitUp,$limitDown);
        if(count($results) != 0)
            if($home == false)
                return $VPal->getResultsVideosSearchPalinsesto($results);
            else
                return $VPal->getResultsVideosSearchHome($results);
        else
            return false;
    }
    
    public function vidwiz_checkPagination(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $session = USingleton_vidwiz::getInstances("USession_vidwiz");
        $VPal = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        global $config;
        $category = $session->getSession("categorySearch");
        $date =  $session->getSession("dateSearch");
        $metatags =  $session->getSession("metatagSearch");
        $limitUp =  $session->getSession("limit");
        if(!isset($limitUp))
            $limitUp = $config['searchLimitPalinsestoAdmin'];
        $lastLimitDown = $session->getSession('lastLimitDown');
        $return = $this->checkPagination($date,$metatags,$category,$lastLimitDown,$limitUp);
        $output = "|beg|"; $i=0; 
        foreach($return as $key=>$value){
            if($value == "" || is_null($value)) $value="0";
            $output .= $key."|x|".$value;
            if($i<count($return)-1)
                $output .="|xxx|";
            $i++;

        }
        $output .= "|end|";
        
        return $output;
    }
    
    public function vidwiz_home(){
        $VPal = USingleton_vidwiz::getInstances("VPalinsesto_vidwiz");
        return $VPal->getHome();
    }
} // end of CPalinsesto
?>
